package com.wsc.wisdomchina.fragment;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.umeng.analytics.MobclickAgent;
import com.wsc.wisdomchina.R;
import com.wsc.wisdomchina.Tools.ACache;
import com.wsc.wisdomchina.Tools.JsonTools;
import com.wsc.wisdomchina.Tools.Tools;
import com.wsc.wisdomchina.activitity.JieDaoTeSheActivity;
import com.wsc.wisdomchina.activitity.JuWeiXinXiActivity;
import com.wsc.wisdomchina.activitity.LifeServerActivity;
import com.wsc.wisdomchina.activitity.LivingExpensesActivity;
import com.wsc.wisdomchina.activitity.PageInfoDetailActivity;
import com.wsc.wisdomchina.activitity.PeripheralSearchActivity;
import com.wsc.wisdomchina.activitity.ReceptionCenterActivity;
import com.wsc.wisdomchina.activitity.ShangjiaCuXiaoActivity;
import com.wsc.wisdomchina.activitity.fourmodule.CompanyInfoActivity;
import com.wsc.wisdomchina.activitity.fourmodule.FloorEventActivity;
import com.wsc.wisdomchina.activitity.fourmodule.FloorInfoActivity;
import com.wsc.wisdomchina.activitity.fourmodule.HelpOldManActivity;
import com.wsc.wisdomchina.activitity.fourmodule.PeopleControlActivity;
import com.wsc.wisdomchina.activitity.introduction.BriefIntroductionActivity;
import com.wsc.wisdomchina.activitity.wisdomParty.PartyActivity;
import com.wsc.wisdomchina.activitity.wisdomParty.PartyLoginActivity;
import com.wsc.wisdomchina.adapter.ConvenienceAdapter;
import com.wsc.wisdomchina.adapter.ModuleAdapter;
import com.wsc.wisdomchina.application.MyApplication;
import com.wsc.wisdomchina.callback.ContributorView;
import com.wsc.wisdomchina.constant.Constant;
import com.wsc.wisdomchina.education.activity.EducationActivity;
import com.wsc.wisdomchina.houselease.activity.HouseLeaseActivity;
import com.wsc.wisdomchina.javaBean.ConvenienceModuleListBean;
import com.wsc.wisdomchina.javaBean.HomeModule;
import com.wsc.wisdomchina.javaBean.HomeModuleBean;
import com.wsc.wisdomchina.javaBean.RespObj;
import com.wsc.wisdomchina.javaBean.StreetInfoListBean;
import com.wsc.wisdomchina.javaBean.wisdomParty.PartyUserBean;
import com.wsc.wisdomchina.jobhunt.activity.JobHuntActivity;
import com.wsc.wisdomchina.notice.activity.AnnouncementListActivity;
import com.wsc.wisdomchina.presenter.ContributorPresenter;
import com.wsc.wisdomchina.view.MyGridView;
import com.wsc.wisdomchina.view.MyToast;
import com.wsc.wisdomchina.welfare.activity.WelfareEventActivity;

import java.util.List;

public class ConvenienceFragment extends Fragment implements View.OnClickListener, ContributorView {
    private boolean ishide = false;
    private ContributorPresenter contributorPresenter;
    private Context context;
    private PullToRefreshListView lv_today_information;
    private ListView actualListView;
    private String cidNumber;
    private MyApplication myApplication;
    private final String HOMEMODULELISTFLAG = "HOMEMODULELISTFLAG";
    private ACache aCache;
    private String aCacheFlagKey = ConvenienceFragment.class.getSimpleName();
    private ListStockAdapter listStockAdapter;
    private MyToast myToast;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_convenience, container, false);
        context = getActivity();
        myToast = new MyToast(context);
        aCache = ACache.get(context);
        myApplication = (MyApplication) getActivity().getApplication();
        contributorPresenter = new ContributorPresenter(this, context);
        String locationString = Tools.getSharedPreferencesStrings(Constant.SharePreferenceLocation, "", context);
        if (locationString.length() > 0) {
            StreetInfoListBean streetInfoListBean = JsonTools.jsonStringToObject(locationString, StreetInfoListBean.class);
            cidNumber = streetInfoListBean.getId();
        }
        initview(view);
        return view;
    }

    private void initview(View view) {
        lv_today_information = (PullToRefreshListView) view.findViewById(R.id.lv_today_information);
        lv_today_information.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        actualListView = lv_today_information.getRefreshableView();
        ImageView image = new ImageView(getActivity());
        image.setImageResource(R.drawable.wodedix_title_);
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,30);
        image.setLayoutParams(params);
        actualListView.addFooterView(image);
        actualListView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        Tools.showRefreshView(lv_today_information);

        lv_today_information.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                // Update the LastUpdatedLabe
                // 处理下拉刷新的业务
                if (refreshView.getCurrentMode().equals(PullToRefreshBase.Mode.PULL_FROM_START)) {
                    if (cidNumber != null) {
                        //获取新闻消息
                        contributorPresenter.getConvenienceModule(cidNumber, HOMEMODULELISTFLAG);
                    }
                }

            }
        });
    }


    private void getData() {
        if (listStockAdapter == null) {
            if (aCache.getAsString(aCacheFlagKey) != null) {
                Gson gson = new Gson();
                ConvenienceModuleListBean moduleList  = gson.fromJson(aCache.getAsString(aCacheFlagKey),ConvenienceModuleListBean.class);
                List<ConvenienceModuleListBean.ConvenienceModule> homeModuleBeanList = moduleList.getObj();
                if (homeModuleBeanList != null && homeModuleBeanList.size() > 0) {
                    listStockAdapter = new ListStockAdapter(homeModuleBeanList);
                    actualListView.setAdapter(listStockAdapter);
                }
            } else {
                if (cidNumber != null) {
                    //获取新闻消息
                    contributorPresenter.getConvenienceModule(cidNumber, HOMEMODULELISTFLAG);
                }
            }
        }

    }

    @Override
    public void onLoadContributorStart(String flag) {

    }

    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
//        Log.e("http", flag + ":" + jsonString);
        try {
            //banner
            if (flag.equals(HOMEMODULELISTFLAG)) {
                Gson gson = new Gson();
                ConvenienceModuleListBean moduleList  = gson.fromJson(jsonString,ConvenienceModuleListBean.class);

                if (moduleList.getCode() == 200) {
                    List<ConvenienceModuleListBean.ConvenienceModule> homeModuleBeanList = moduleList.getObj();
                    if (homeModuleBeanList != null && homeModuleBeanList.size() > 0) {
                        aCache.put(aCacheFlagKey, jsonString, 8 * 60);
                        listStockAdapter = new ListStockAdapter(homeModuleBeanList);
                        actualListView.setAdapter(listStockAdapter);
                    }
                }

            }
        } catch (Exception e) {

        }
    }

    /**
     * @author jaily.zhang
     * @version V1.3.1
     * @Description 股票适配器
     * @date 2014-9-9 下午3:39:03
     */
    class ListStockAdapter extends BaseAdapter {
        List<ConvenienceModuleListBean.ConvenienceModule> homeModuleBeanList;

        public ListStockAdapter(List<ConvenienceModuleListBean.ConvenienceModule> listPlansBeans) {
            this.homeModuleBeanList = listPlansBeans;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return homeModuleBeanList.size();
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return homeModuleBeanList.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            try {
                NestedListview v = null;
                if (convertView == null) {
                    v = new NestedListview(context, position,homeModuleBeanList.get(position));
                    convertView = v.getView();
                    convertView.setTag(v.getView());
                } else {
                    v = new NestedListview(context, position,homeModuleBeanList.get(position));
                    convertView = v.getView();
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
            return convertView;
        }

    }

    /**
     * @author jaily.zhang
     * @version V1.3.1
     * @Description 嵌套listView
     * @date 2015-1-9 下午12:57:17
     */
    class NestedListview {

        private View myview;
        private ConvenienceModuleListBean.ConvenienceModule homeModuleBean;
        private Context mycontext;
        private MyGridView myGridView;
        private ImageView tv_title;
        private ConvenienceAdapter adapter;
        private List<ConvenienceModuleListBean.ConvenienceModule.ConvenienceItem> homeModuleList;
        private TextView mTitle;

        public NestedListview(Context context, int position,ConvenienceModuleListBean.ConvenienceModule listData) {
            this.mycontext = context;
            this.homeModuleBean = listData;
            if (listData.getChildren() != null) {
                    homeModuleList = listData.getChildren();
                    if (homeModuleList != null && homeModuleList.size() > 0) {
                        this.adapter = new ConvenienceAdapter(context, homeModuleList, true);
                    }

            }
            InitView(position);
        }

        private void InitView(int position) {
            // TODO Auto-generated method stub
            try {
                myview = LayoutInflater.from(mycontext).inflate(R.layout.convenience_item_layout, null);
                myGridView = (MyGridView) myview.findViewById(R.id.mygridview);
                myGridView.setHaveScrollbar(false);
                mTitle = (TextView) myview.findViewById(R.id.tv_title);
                tv_title = (ImageView) myview.findViewById(R.id.iv_title);
                mTitle.setText(homeModuleBean.getName());
                if(position == 0){
                    tv_title.setImageResource(R.drawable.chengshizb_icon_);
                }else{
                    tv_title.setImageResource(R.drawable.bianmindt_icon_);
                }
/*                Glide.with(context).load(object.getIcon())
                        .placeholder(R.mipmap.own_pic_logout)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(tv_title);*/
                myGridView.setAdapter(adapter);
                myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        ConvenienceModuleListBean.ConvenienceModule.ConvenienceItem homeModule = homeModuleList.get(position);
                        String nameModule = homeModule.getName();
                        //String idModule = homeModule.getMid();
                        String idModule = homeModule.getShortName();
                        if (idModule.equals("sqjj")) {
                            //社区简介
//                            Intent intent = new Intent(context, PageInfoDetailActivity.class);
                            Intent intent = new Intent(context, BriefIntroductionActivity.class);
                            intent.putExtra("id", idModule);
                            intent.putExtra("name", nameModule);
                            startActivity(intent);
                        } else if (idModule.equals("gkgs")) {
//                            //公开公示
                            Intent intent=new Intent(context, AnnouncementListActivity.class);
                            intent.putExtra("id", idModule);
                            intent.putExtra("name", nameModule);
                            intent.putExtra("id",cidNumber);
                            intent.putExtra("tab",0);
                            startActivity(intent);
                        } else if (idModule.equals("tzgg")) {
//                            //通知公告
                            Intent intent=new Intent(context, AnnouncementListActivity.class);
                            intent.putExtra("id", idModule);
                            intent.putExtra("name", nameModule);
                            intent.putExtra("id",cidNumber);
                            intent.putExtra("tab",1);
                            startActivity(intent);
                        } else if (idModule.equals("bgzn")) {
                            //办公职能
                            Intent intent = new Intent(context, PageInfoDetailActivity.class);
                            intent.putExtra("id", idModule);
                            intent.putExtra("name", nameModule);
                            startActivity(intent);
                        } else if (idModule.equals("sqxx")) {
                            //社区信息
                            Intent intent = new Intent(context, JuWeiXinXiActivity.class);
                            intent.putExtra("id", cidNumber);
                            intent.putExtra("name", nameModule);
                            startActivity(intent);
                        } else if (idModule.equals("wggl")) {
                            //网格管理
                            Intent intent = new Intent(context, PageInfoDetailActivity.class);
                            intent.putExtra("id", idModule);
                            intent.putExtra("name", nameModule);
                            startActivity(intent);
                        } else if (idModule.equals("sqts")) {
                            //社区特色
                            Intent intent = new Intent(context, JieDaoTeSheActivity.class);
                            intent.putExtra("id", cidNumber);
                            intent.putExtra("name", nameModule);
                            intent.putExtra("idmodule", idModule);
//                            Log.e("Liu", "onItemClick: " + cidNumber + " " + nameModule + " " + idModule);
                            startActivity(intent);
                        } else if (idModule.equals("zbkc")) {
                            //周边快查
                            Intent intent = new Intent(context, PeripheralSearchActivity.class);
                            intent.putExtra("id", cidNumber);
                            intent.putExtra("name", nameModule);
                            startActivity(intent);
                        }
//                        else if(nameModule.equals("关心青少年"))
//                        {
//                            Intent intent=new Intent(context, CareTeenagersActivity.class);
//                            intent.putExtra("cid",cidNumber);
//                            startActivity(intent);
//                        }
                        else if (idModule.equals("shjf")) {
                            //生活缴费
//                            myToast.showShort("该功能正在升级中，请稍后...");
                            Intent intent = new Intent(context, LivingExpensesActivity.class);
                            intent.putExtra("name", nameModule);
                            intent.putExtra("cid", cidNumber);
                            startActivity(intent);
                        } else if (idModule.equals("shfw")) {
                            //生活服务
                            Intent intent = new Intent(context, LifeServerActivity.class);
                            intent.putExtra("id", cidNumber);
                            intent.putExtra("name", nameModule);
                            startActivity(intent);
                        } else if (idModule.equals("sjcx")) {
                            //商家促销
                            Intent intent = new Intent(context, ShangjiaCuXiaoActivity.class);
                            intent.putExtra("id", cidNumber);
                            intent.putExtra("name", nameModule);
                            startActivity(intent);
                        } else if (idModule.equals("lyxx")) {
                            //楼宇信息
                            Intent intent = new Intent(context, FloorInfoActivity.class);
                            intent.putExtra("name", "楼宇搜索");
                            intent.putExtra("id", cidNumber);
                            startActivity(intent);
                        } else if (idModule.equals("qzzp")) {//求职招聘
                            Intent intent = new Intent(context, JobHuntActivity.class);
                            intent.putExtra("name", "求职招聘");
                            intent.putExtra("id", cidNumber);
                            startActivity(intent);
                        } else if (idModule.equals("fwzl")) {//房屋租赁
                            Intent intent = new Intent(context, HouseLeaseActivity.class);
                            intent.putExtra("name", "房屋租赁");
                            intent.putExtra("id", cidNumber);
                            startActivity(intent);
                        } else if (idModule.equals("jypx")) {//教育培训
                            Intent intent = new Intent(context, EducationActivity.class);
                            intent.putExtra("name", "教育培训");
                            intent.putExtra("id", cidNumber);
                            startActivity(intent);
                        } else if (idModule.equals("sqgy")) {//社区公益
                            Intent intent = new Intent(context, WelfareEventActivity.class);
                            intent.putExtra("name", "社区公益");
                            intent.putExtra("id", cidNumber);
                            startActivity(intent);
                        } else if (idModule.equals("qyxx")) {
                            //企业信息
                            Intent intent = new Intent(context, CompanyInfoActivity.class);
                            intent.putExtra("name", "企业搜索");
                            intent.putExtra("id", cidNumber);
                            startActivity(intent);
                        } else if (idModule.equals("lyhd")) {
                            //楼宇活动
                            Intent intent = new Intent(context, FloorEventActivity.class);
                            intent.putExtra("name", nameModule);
                            intent.putExtra("cid", cidNumber);
                            intent.putExtra("type", 1);
                            startActivity(intent);
                        } else if (idModule.equals("sqhd")) {
                            //社区活动
                            Intent intent = new Intent(context, FloorEventActivity.class);
                            intent.putExtra("name", nameModule);
                            intent.putExtra("cid", cidNumber);
                            intent.putExtra("type", 0);
                            startActivity(intent);
                        } else if (idModule.equals("slzx")|| idModule.equals("bsck")) {
                            //受理中心 办事窗口
                            Intent intent = new Intent(context, ReceptionCenterActivity.class);
                            intent.putExtra("id", cidNumber);
                            intent.putExtra("name", nameModule);
                            startActivity(intent);
                        }
//                        else if(nameModule.equals("党员组织管理"))
//                        {
//
//                        }
                        else if (idModule.equals("zlfw")) {
                            //助老服务
                            Intent intent = new Intent(context, HelpOldManActivity.class);
                            intent.putExtra("name", nameModule);
                            intent.putExtra("cid", cidNumber);
                            intent.putExtra("idmodule", idModule);
                            startActivity(intent);
                        } else if (idModule.equals("zcfw")) {
                            //助残服务
                            Intent intent = new Intent(context, HelpOldManActivity.class);
                            intent.putExtra("name", nameModule);
                            intent.putExtra("cid", cidNumber);
                            intent.putExtra("idmodule", idModule);
                            startActivity(intent);
                        } else if (idModule.equals("bxjd")) {
                            // 百姓监督
                            Intent intent = new Intent(context, PeopleControlActivity.class);
                            intent.putExtra("name", nameModule);
                            intent.putExtra("cid", cidNumber);
                            startActivity(intent);
                        } else if (nameModule.equals("智慧党建")) {
                            String jsonMessage = Tools.getSharedPreferencesStrings(Constant.SharePreferencePartyUserInfo, "", context);
                            if (jsonMessage.equals("")) {
                                // 智慧党建
                                Intent intent = new Intent(context, PartyLoginActivity.class);
                                intent.putExtra("name", nameModule);
                                intent.putExtra("cid", cidNumber);
                                startActivity(intent);
                            } else {
                                PartyUserBean partyUserBean = JsonTools.jsonStringToObject(jsonMessage, PartyUserBean.class);
                                Intent intent = new Intent(context, PartyActivity.class);
                                intent.putExtra("pId", partyUserBean.getId());
                                intent.putExtra("cId", cidNumber);
                                startActivity(intent);
                            }
                        }

                    }
                });

            } catch (Exception e) {
                // TODO: handle exception
            }
        }

        public View getView() {
            // TODO Auto-generated method stub
            return myview;
        }
    }

    @Override
    public void onLoadContributorComplete(String flag) {
        lv_today_information.onRefreshComplete();
    }

    @Override
    public void onLoadContributorError(String error, String flag) {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        ishide = hidden;
        if (hidden) {
        } else {
            getData();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (ishide) {

        } else {
            getData();
        }

        MobclickAgent.onPageStart(ConvenienceFragment.class.getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(ConvenienceFragment.class.getSimpleName());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }
}
